package com.zhang.ExcelAnalyze;
import org.apache.logging.log4j.util.PropertiesUtil;
import Util.HttpUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.net.MalformedURLException;
import java.util.*;

/**
 * 开始解析excel文件
 */
public class AnalyzeStart {

    final Integer ip=12;
    final Integer op=12;
    final Integer mr=14;
    final Integer inspect=13;
    private static File file;
   static Properties properties=null;
    static {
         properties=new Properties();
       try {
           properties.load(new InputStreamReader(PropertiesUtil.class.getResourceAsStream("/httpClient.properties")));
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
    public AnalyzeStart(){ }

    /**
     * 找到文件开始解析
     * @param file1
     * @return
     */
    public String FoundExcel(File file1)
    {
        file=file1;
      String message=  this.AnalyzeExcel();
        return message;
    }

    /**
     * 开始解析excel文件
     * @return
     */
    public String AnalyzeExcel()
    {
        try {
            Workbook workbook = WorkbookFactory.create(new FileInputStream(file));

            //获取该excel的每一个子表
       int sheetsLength= workbook.getNumberOfSheets();
        for (int i=0;i<sheetsLength;i++)
        {
            Sheet sheet =workbook.getSheetAt(i);
          boolean s=  this.AnalyzeSheet(sheet);
          if (s==false)
          {
              System.out.println("===================== 文件中第"+(i+1)+"个工作表 "+sheet.getSheetName()+" ===================== ");
              continue;
          }
            System.out.println("===================== 文件中第"+(i+1)+"个工作表 "+sheet.getSheetName()+" 解析成功！=====================");
        }

    }catch (InvalidFormatException e) {
            e.printStackTrace();
        }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
        return "";
    }

    /**
     * 解析具体的Sheet的内容
     * @param sheet
     * @return
     */
    public boolean AnalyzeSheet(Sheet sheet)
    {
        //记录第几行几列的值
        Map<Integer, List<String>> map = new HashMap();
        //记录中文标题行的值
        List<String> cname=new ArrayList<String>();
        //记录文档字段标题的值
        List<String> name=new ArrayList<String>();
        //如果查到有几行数据
        System.out.println("---    "+sheet.getSheetName()+"记录表有："+sheet.getPhysicalNumberOfRows()+"行  ---");

        //测试次数
        int ff=0;
        for (int i=1;i<sheet.getPhysicalNumberOfRows();i++)
        {
            List<String> value=new ArrayList<String>();
            //一个完整的入参
            int number=0;
            String s = sheet.getSheetName();
            //设置列数
            if (s.equals("OP")) {
                number = op;
            }
            if (s.equals("IP")) {
                number = ip;
            }
            if (s.equals("MR"))
            {
                number=mr;
            }
            if (s.equals("INSPECT"))
            {
                number=inspect;
            }
            for (int j=1;j<=number;j++) {
                //判断那个值为空
                if (sheet.getRow(i).getCell(j)==null) {
                    if (i > 2) {
                        value.add("");
                    }
                }else {
                    Cell cell = sheet.getRow(i).getCell(j);
                    String a = cell.getStringCellValue();
                    if (i == 1) {
                        cname.add(a);
                    }
                    if (i == 2) {
                        name.add(a);
                    }
                    if (i > 2) {
                        value.add(a);
                    }
                }
                }
                if (i>2) {
                    map.put((i+1), value);
                }
                ff++;
            }
        System.out.println("--  次数 "+ff+"   --");
        System.out.println(cname);
        System.out.println(name);
        System.out.println(map.toString());

        if (map!=null)
    {
        boolean as=  this.sortingResult(map,name,sheet.getLastRowNum()+1,sheet.getSheetName());
        if (as)
        {
            return true;
        }
    }
     return false;
    }

    /**
     * 整理每一行入参
     */
    public boolean  sortingResult(Map<Integer, List<String>> map, List<String> name,Integer s,String sheetName)
    {

        List<String> value;
        //拿走所有行的值
        int hang=s-3;
        int jisu=0;
        System.out.println("--   该表格共："+s+"行，"+hang+"行数据   --");
        //从第四行数据开始拿
        for (int i=4;i<=s;i++)
        {
            if (map.get(i)==null)
             {
                continue;
             }else {
                value = map.get(i);//只获取了0
              boolean ass=  this.AnalyzeJson(name, value,sheetName);
              if (ass)
               {
                  System.out.println("Excel第"+i+"行的值插入成功！第"+(i-3)+"个数据插入成功！");
                   jisu ++;
               }else {
                  System.out.println("Excel第"+i+"行的值插入失败！第"+(i-3)+"个数据插入失败！");
              }
             }
            }
            if (jisu == map.size())
            {
                return true;
            }
        System.out.println("--   一共尝试获取数据"+map.size()+"次  --");
        return false;
        }
    /**
     * 转换成json
     * @return
     */
    public  boolean AnalyzeJson(List<String> name,List<String> value,String sheetName) {
        System.out.println("-------------------------------  入参  ---------------------------------");
        Map<String,String> map=new HashMap<String, String>();
        for (int i=0;i<name.size();i++)
        {
               map.put(name.get(i),value.get(i));
        }
        if (sheetName.equals("OP")) {
            String reqOp = "{\n" +
                    "    \"dataContent\":[\n" +
                    "        {\n" +
                    "            \"hospitalId\":" + map.get("hospitalId") + ",\n" +
                    "            \"provider_id\":" + map.get("provider_id") + ",\n" +
                    "            \"insuranceName\":\"" + map.get("insuranceName") + "\",\n" +
                    "            \"insuranceCertNo\":\"" + map.get("insuranceCertNo") + "\",\n" +
                    "            \"insuranceCertType\":\"" + map.get("insuranceCertType") + "\",\n" +
                    "            \"startDate\":\"" + map.get("startDate") + "\",\n" +
                    "            \"endDate\":\"" + map.get("endDate") + "\",\n" +
                    "            \"medicalNum\":\"" + map.get("medicalNum") + "\",\n" +
                    "            \"medicalCardNum\":\"" + map.get("medicalCardNum") + "\",\n" +
                    "            \"outPatientNum\":\"" + map.get("outPatientNum") + "\",\n" +
                    "            \"medicalBillingNo\":\""+map.get("medicalBillingNo")+"\",\n" +
                    "            \"invoiceNo\":\""+map.get("invoiceNo")+"\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";
            System.out.println(reqOp);
            String urlOp =properties.getProperty("opSettlement");
            String message= null;
            try {
                message = HttpUtil.doHttp(urlOp,reqOp);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            if (message.equals("error"))
            {
                return false;
            }else {
                return true;
            }
        }
        if (sheetName.equals("IP")) {
            String reqIp = "{\n" +
                    "    \"dataContent\":[\n" +
                    "        {\n" +
                    "            \"hospitalId\":"+map.get("hospitalId")+",\n" +
                    "            \"provider_id\":"+map.get("provider_id")+",\n" +
                    "            \"insuranceCertNo\":\""+map.get("insuranceCertNo")+"\",\n" +
                    "            \"medicalBillingNo\":\""+map.get("medicalBillingNo")+"\",\n" +
                    "            \"medicalNum\":\""+map.get("medicalNum")+"\",\n" +
                    "            \"endDate\":\""+map.get("endDate")+"\",\n" +
                    "            \"medicalCardNum\":\""+map.get("medicalCardNum")+"\",\n" +
                    "            \"insuranceName\":\""+map.get("insuranceName")+"\",\n" +
                    "            \"insuranceCertType\":\""+map.get("insuranceCertType")+"\",\n" +
                    "            \"invoiceNo\":\""+map.get("invoiceNo")+"\",\n" +
                    "            \"startDate\":\""+map.get("startDate")+"\",\n" +
                    "            \"inHospitalNum\":\""+map.get("inHospitalNum")+"\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}\n";
            System.out.println(reqIp);

            String urlIp = properties.getProperty("ipSettlement");
            String message= null;
            try {
                message = HttpUtil.doHttp(urlIp,reqIp);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            if (message.equals("error"))
            {
                return false;
            }else {
                return true;
            }
        }
        if (sheetName.equals("MR")) {
            String reqMr = "{\n" +
                    "    \"dataContent\":[\n" +
                    "        {\n" +
                    "            \"hospitalId\":"+map.get("hospitalId")+",\n" +
                    "            \"provider_id\":"+map.get("provider_id")+",\n" +
                    "            \"insuranceCertNo\":\""+map.get("insuranceCertNo")+"\",\n" +
                    "            \"medicalBillingNo\":\""+map.get("medicalBillingNo")+"\",\n" +
                    "            \"medicalNum\":\""+map.get("medicalNum")+"\",\n" +
                    "            \"endDate\":\""+map.get("endDate")+"\",\n" +
                    "            \"outOrInIdentify\":\""+map.get("outOrInIdentify")+"\",\n" +
                    "            \"medicalCardNum\":\""+map.get("medicalCardNum")+"\",\n" +
                    "            \"insuranceName\":\""+map.get("insuranceName")+"\",\n" +
                    "            \"insuranceCertType\":\""+map.get("insuranceCertType")+"\",\n" +
                    "            \"invoiceNo\":\""+map.get("invoiceNo")+"\",\n" +
                    "            \"startDate\":\""+map.get("startDate")+"\",\n" +
                    "            \"outpatientNo\":\""+map.get("outpatientNo")+"\",\n" +
                    "            \"inHospitalNum\":\""+map.get("inHospitalNum")+"\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}\n";
            System.out.println(reqMr);
            String urlMr =properties.getProperty("mrSettlement");
            String message= null;
            try {
                message = HttpUtil.doHttp(urlMr,reqMr);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            if (message.equals("error"))
            {
                return false;
            }else {
                return true;
            }
        }
        if (sheetName.equals("INSPECT")) {
            String reqInsp = "{\n" +
                    "    \"dataContent\":[\n" +
                    "        {\n" +
                    "            \"hospitalId\":"+map.get("hospitalId")+",\n" +
                    "            \"provider_id\":"+map.get("provider_id")+",\n" +
                    "            \"insuranceName\":\""+map.get("insuranceName")+"\",\n" +
                    "            \"insuranceCertNo\":\""+map.get("insuranceCertNo")+"\",\n" +
                    "            \"insuranceCertType\":\""+map.get("insuranceCertType")+"\",\n" +
                    "            \"startDate\":\""+map.get("startDate")+"\",\n" +
                    "            \"medicalType\":\""+map.get("medicalType")+"\",\n" +
                    "            \"serviceClassification\":\""+map.get("serviceClassification")+"\",\n" +
                    "            \"endDate\":\""+map.get("endDate")+"\",\n" +
                    "            \"medicalNum\":\""+map.get("medicalNum")+"\",\n" +
                    "            \"medicalCardNum\":\""+map.get("medicalCardNum")+"\",\n" +
                    "            \"outPatientNum\":\""+map.get("outPatientNum")+"\",\n" +
                    "            \"inHospitalNum\":\""+map.get("inHospitalNum")+"\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}\n";
            System.out.println(reqInsp);
            String urlMr =properties.getProperty("inspectSettlement");
            String message= null;
            try {
                message = HttpUtil.doHttp(urlMr,reqInsp);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            if (message.equals("error"))
            {
                return false;
            }else {
                return true;
            }
        }

        return  false;
 }
}
